package com.example.yuntiku.Servlet;

import com.example.yuntiku.Email.SendEmail;
import com.example.yuntiku.dao.impl.UsersDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

@WebServlet(name = "UpdatePwServlet", value = "/UpdatePwServlet")
public class UpdatePwServlet extends HttpServlet {
    private static String emails;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            String email = request.getParameter("email"); // 获取邮箱
            SendEmail sendEmail = new SendEmail();           //定义发送邮件工具类
            String message = sendEmail.generateCaptcha();    //调用工具类的生成验证码方法
            sendEmail.send(email, message);                  //发送邮件
            // 存储邮箱和验证码到session
            HttpSession session = request.getSession();
            session.setAttribute("message", message);
            session.setAttribute("email", email);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 处理乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        // 获得请求参数
        String email = request.getParameter("email");
        String code = request.getParameter("code");  // 注意这里使用小写的 Code

        PrintWriter printWriter = response.getWriter();

        // 从session中取出邮箱和验证码
        HttpSession session = request.getSession();
        String storedEmail = (String) session.getAttribute("email");
        String storedMessage = (String) session.getAttribute("message");

        // 验证邮箱是否存在于数据库中
        UsersDao usersDao = new UsersDao();

        // 检查邮箱是否已注册
        if (!usersDao.isEmailRegistered(email)) {
            printWriter.println("邮箱未注册");
            return;
        }

        // 如果邮箱和验证码匹配，并且邮箱存在于数据库中
        if (Objects.equals(email, storedEmail) && Objects.equals(code, storedMessage)) {
            request.getSession().setAttribute("email",email);
            // 重定向至修改密码页面
            response.sendRedirect("forgot_password.jsp");
        } else {
            printWriter.println("验证码错误或者邮箱错误");
        }
    }
}